package com.apache.info.service.impl;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.util.Validator;
import com.apache.database.db.IDao;
import com.apache.database.exception.DaoAccessException;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.info.entity.PubMetadata;
import com.apache.info.entity.PubSortInfo;
import com.apache.info.manager.PubSortInfoManager;
import com.apache.info.util.InfoMap;
import com.apache.info.util.MessageUtil;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PubSortInfoManagerImpl implements PubSortInfoManager {

	protected IDao pubSortInfoDao;
	protected IDao pubMetadataDao;
	protected final String entityName = "com.apache.info.entity.PubSortInfo";
	private Map<String, String> metadatas;

	public void setPubSortInfoDao(IDao pubSortInfoDao) {
		this.pubSortInfoDao = pubSortInfoDao;
	}

	public void setPubMetadataDao(IDao pubMetadataDao) {
		this.pubMetadataDao = pubMetadataDao;
	}

	public void setMetadatas(Map<String, String> metadatas) {
		this.metadatas = metadatas;
	}

	public String saveInfo(ParamsVo<PubSortInfo> vo) throws BusinessException {
		PubSortInfo pubSortInfo = vo.getObj();
		String infoId = pubSortInfo.getSortId();
		if (Validator.isNull(pubSortInfo.getSortId())) {
			infoId = Validator.generate();
		}
		pubSortInfo.setCreateTime(DateUtils.Now.fmt_yyyyMMdd_HHmmss());
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";//"pubSortInfo_" + pubSortInfo.getSortCode();
		pubSortInfo.setSortId(infoId);
		if (Validator.isNull(pubSortInfo.getSysName())) {
			pubSortInfo.setSysName("plateform");
		}
		MethodParam param = new MethodParam("PubSortInfo", cacheKey, "", entityName);
		param.setVaule(pubSortInfo);
		if (pubSortInfoDao.insert(param)) {
			if (!saveMetadatas(pubSortInfo, Validator.getDefaultStr(String.valueOf(vo.getParams("mainTab")), "0")))
				throw new BusinessException("创建元素失败");
			return infoId;
		}
		return "";
	}

	/**
	 * description:  自动生成公共元素字段
	 */
	private boolean saveMetadatas(PubSortInfo info, String mainTab) {
		List<PubMetadata> list = new ArrayList<PubMetadata>();
		boolean mark = false;
		List<InfoMap> dfList = null;
		try {
			MethodParam mparam = new MethodParam("InfoRelease", "", "", entityName);
			mparam.setParams("dyncSql", "select * from pub_default_field where sys_name='" + info.getSysName() + "'");
			dfList = pubSortInfoDao.select(mparam);
		}catch (DaoAccessException e){
		}
		StringBuffer attrs = new StringBuffer();
		Map<String, String> cloumn = new HashMap<String, String>();
		String primaryKey = "";
		if(Validator.isEmpty(dfList)) {
			if (null == metadatas && Validator.isEmpty(metadatas)) {
				return true;
			}
			if ("1".equals(mainTab)) {
				int count = 1;
				for (String key : metadatas.keySet()) {
					PubMetadata m1 = new PubMetadata();
					m1.setMetadataId(Validator.generate());
					m1.setSortId(info.getSortId());
					String str[] = metadatas.get(key).split(",");
					m1.setDataFullName(str[0]);
					m1.setDataAttr(key);
					m1.setDataShortName(str[1]);
					m1.setDataLength(Long.valueOf(str[2]));
					m1.setDataRestrict(str[3]);
					m1.setDataType(str[4]);
					m1.setIfAdd("F");
					m1.setIfEdit("F");
					m1.setIfList("F");
					m1.setIfSearch("F");
					m1.setReserved2("T");
					m1.setReserved1(String.valueOf(count));
					m1.setCreateTime(DateUtils.Now.fmt_yyyyMMdd_HHmmss());
					attrs.append("," + key);
					cloumn.put(key, str[4]);
					if ("1".equals(str[3])) {
						primaryKey = str[1];
					}
					count++;
					list.add(m1);
				}
			} else {
				PubMetadata m1 = new PubMetadata();
				m1.setMetadataId(Validator.generate());
				m1.setSortId(info.getSortId());
				m1.setDataFullName("主键");
				m1.setDataAttr("subId");
				m1.setDataShortName("sub_id");
				m1.setDataLength(36l);
				m1.setDataRestrict("1");
				m1.setDataType("5");
				m1.setReserved2("T");
				m1.setReserved1("1");
				m1.setCreateTime(DateUtils.Now.fmt_yyyyMMdd_HHmmss());
				attrs.append(",subId");
				cloumn.put("subId", "5");
				primaryKey = "sub_id";
				list.add(m1);
			}
		} else {//系统配置的表默认字段
			for(InfoMap<Object> dmap : dfList){
				PubMetadata m1 = new PubMetadata();
				m1.setMetadataId(Validator.generate());
				m1.setSortId(info.getSortId());
				m1.setDataFullName(String.valueOf(dmap.get("fieldCname")));
				m1.setDataAttr(String.valueOf(dmap.get("attrName")));
				m1.setDataShortName(String.valueOf(dmap.get("fieldEname")));
				m1.setDataLength(Long.valueOf(Validator.getDefaultStr(String.valueOf(dmap.get("fieldLength")),"50")));
				m1.setDataRestrict(String.valueOf(dmap.get("dataRestrict")));
				m1.setDataType(String.valueOf(dmap.get("fieldType")));
				m1.setIfAdd("F");
				m1.setIfEdit("F");
				m1.setIfList("F");
				m1.setIfSearch("F");
				m1.setReserved2("T");
				m1.setReserved1(Validator.getDefaultStr(String.valueOf(dmap.get("dataOrder")),"10"));//序号
				m1.setCreateTime(DateUtils.Now.fmt_yyyyMMdd_HHmmss());
				attrs.append(","+String.valueOf(dmap.get("attrName")));
				cloumn.put(String.valueOf(dmap.get("attrName")), "5");
				if ("1".equals(dmap.get("dataRestrict"))) {
					primaryKey = String.valueOf((dmap.get("fieldEname")));
				}
				list.add(m1);
			}
		}
		MethodParam param = new MethodParam("PubMetadata", "", "", PubMetadata.class.getName());
		param.setVaule(list);
		mark = pubMetadataDao.insertBath(param);
		String cacheKey = MessageUtil.getTableCacheKey(info.getSortCode(), info.getSysName(), "_tableAttr");
		String cacheKey2 = MessageUtil.getTableCacheKey(info.getSortCode(), info.getSysName(), "_tableMaps");
		String cacheContent = cacheKey + ";" + attrs.substring(1).toString() + ";" + primaryKey + ";"
				+ info.getInfoTableName();
		getCache().createCacheObject(cacheKey, cacheContent);
		getCache().createCacheObject(cacheKey2, cloumn);
		return mark;
	}

	public boolean editInfo(ParamsVo<PubSortInfo> vo) throws BusinessException {
		PubSortInfo pubSortInfo = vo.getObj();
		if (Validator.isNotNull(pubSortInfo.getSortId())) {
			MethodParam param = new MethodParam("ById", "", "", entityName);
			param.setInfoId(pubSortInfo.getSortId());
			PubSortInfo oldInfo = (PubSortInfo) pubSortInfoDao.selectById(param);
			//			String cacheKey = "pubSortInfo_" + pubSortInfo.getSortCode();
			param = new MethodParam("PubSortInfo", "", "", entityName);
			pubSortInfo.setCreateTime(DateUtils.Now.fmt_yyyyMMdd_HHmmss());//因无modify_time字段，则修改时同步更新创建时间
			param.setVaule(pubSortInfo);
			boolean mark = pubSortInfoDao.edit(param);
			if (Validator.isNotNull(oldInfo.getSortCode()) && Validator.isNotNull(pubSortInfo.getSortCode())) {
				if (mark && !oldInfo.getSortCode().equals(pubSortInfo.getSortCode())) {
					//					getCache().removeCacheObject("pubSortInfo_" + oldInfo.getSortCode());
					getCache().removeCacheObject(
							MessageUtil.getTableCacheKey(oldInfo.getSortCode(), oldInfo.getSysName(), "_tableAttr"));
					getCache().removeCacheObject(
							MessageUtil.getTableCacheKey(oldInfo.getSortCode(), oldInfo.getSysName(), "_tableMaps"));
					setPublishTable(pubSortInfo.getSortCode(), pubSortInfo.getSortId(), pubSortInfo.getSysName(),
							pubSortInfo.getInfoTableName());
				}
			}
			return mark;
		}
		return false;
	}

	/**
	 * 生成表缓存
	 */
	private void setPublishTable(String sortCode, String sortId, String sysName, String tableName) {
		MethodParam param = new MethodParam("ByProperty", "", "", PubMetadata.class.getName());
		param.setParams("sortId", sortId);
		param.setResultCache(false);
		List<PubMetadata> list = pubSortInfoDao.select(param);
		if (null == list || list.isEmpty())
			return;
		String primaryKey = "";
		String primaryKeys = "";
		Map<String, String> cloumn = new HashMap<String, String>();
		StringBuilder attrs = new StringBuilder();
		for (PubMetadata pm : list) {
			if ("F".equalsIgnoreCase(pm.getReserved2()))//虚字段不加入
				continue;
			attrs.append("," + pm.getDataAttr());
			cloumn.put(pm.getDataAttr(), pm.getDataType());
			if ("1".equals(pm.getDataRestrict())) {//唯一主键
				primaryKey = pm.getDataShortName();
			} else if ("4".equals(pm.getDataRestrict())) {//联合主键
				primaryKeys += "," + pm.getDataShortName();
			}
		}
		if (Validator.isNotNull(primaryKeys)) {
			primaryKeys = primaryKeys.substring(1);
		}
		primaryKey = Validator.getDefaultStr(primaryKey, primaryKeys);
		String cacheContent = "PubMetata;" + attrs.substring(1).toString() + ";" + primaryKey + ";" + tableName;
		getCache().createCacheObject(MessageUtil.getTableCacheKey(sortCode, sysName, "_tableAttr"), cacheContent);
		getCache().createCacheObject(MessageUtil.getTableCacheKey(sortCode, sysName, "_tableMaps"), cloumn);
	}

	public boolean deleteInfo(ParamsVo<PubSortInfo> vo) throws BusinessException {
		String infoId = vo.getInfoId();
		if (Validator.isNull(infoId)) {
			return false;
		}
		//		String cacheKey = "pubSortInfo_" + infoId;
		//String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
		MethodParam param = new MethodParam("ById", "", "", entityName);
		param.setInfoId(infoId);
		PubSortInfo oldInfo = (PubSortInfo) pubSortInfoDao.selectById(param);
		param.setParams("sortId", infoId);
		param.setDelete(true);
		boolean mark = pubSortInfoDao.delete(param);
		if (mark) {
			//			getCache().removeCacheObject("pubSortInfo_" + oldInfo.getSortCode());
			getCache().removeCacheObject(
					MessageUtil.getTableCacheKey(oldInfo.getSortCode(), oldInfo.getSysName(), "_tableAttr"));
			getCache().removeCacheObject(
					MessageUtil.getTableCacheKey(oldInfo.getSortCode(), oldInfo.getSysName(), "_tableMaps"));
		}
		return mark;
	}

	public Object getInfoById(ParamsVo<PubSortInfo> vo) {
		String infoId = vo.getInfoId();
		if (Validator.isNull(infoId)) {
			return null;
		}
		String methKey = Validator.getDefaultStr(vo.getMethodKey(), "ById");
		String cacheKey = "";
		MethodParam param = new MethodParam(methKey, cacheKey, "", entityName);
		if ("BySortCode".equalsIgnoreCase(methKey)) {
			//			cacheKey = "pubSortInfo_" + infoId;
			param.setCacheId(cacheKey);
			param.setParams("sortCode", infoId);
			param.setParams("sysName", StrUtil.doNull(String.valueOf(vo.getParams("sysName")), "plateform"));
			return pubSortInfoDao.selectSingle(param);
		} else {
			param.setInfoId(infoId);
			return pubSortInfoDao.selectById(param);
		}
	}

	public Object execute(ParamsVo<PubSortInfo> vo) {
		//		String key = vo.getMethodKey();
		//		if (key.equalsIgnoreCase("publishTable")) {//发布表生成缓存
		//			PubSortInfo info = vo.getObj();
		//			setPublishTable(info.getSortCode(), info.getSortId(), info.getSysName(), info.getInfoTableName());
		//		}
		return null;
	}

	public Page getPageInfo(ParamsVo<PubSortInfo> vo) {
		MethodParam param = setMethodParams(vo, 2);
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		Page page = pubSortInfoDao.pageSelect(param);
		return page;
	}

	public List<PubSortInfo> getList(ParamsVo<PubSortInfo> vo) {
		MethodParam param = setMethodParams(vo, 2);
		return pubSortInfoDao.select(param);
	}

	public long countInfo(ParamsVo<PubSortInfo> vo) {
		MethodParam param = setMethodParams(vo, 1);
		return pubSortInfoDao.count(param);
	}

	private MethodParam setMethodParams(ParamsVo<PubSortInfo> vo, int type) {
		String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
		MethodParam param = new MethodParam(methodKey, "", "", entityName);
		PubSortInfo pubSortInfo = vo.getObj();
		String ids = String.valueOf(vo.getParams("sortIds"));
		if (Validator.isNotNull(ids)) {
			param.setParams("sortIds", StrUtil.strArrayToStr(ids.split(","), ",", "'"));
		}
		if (Validator.isEmpty(pubSortInfo))
			return param;
		if (Validator.isNotNull(pubSortInfo.getSortCode())) {
			param.setParams("sortCode", pubSortInfo.getSortCode());
		}
		if (Validator.isNotNull(pubSortInfo.getSortName())) {
			param.setParams("sortName", pubSortInfo.getSortName());
		}
		if (Validator.isNotNull(pubSortInfo.getSysName())) {
			param.setParams("sysName", pubSortInfo.getSysName());
		}
		if (Validator.isNotNull(pubSortInfo.getInfoTableName())) {
			param.setParams("infoTableName", pubSortInfo.getInfoTableName());
		}
		if (Validator.isNotNull(pubSortInfo.getSortStatus())) {
			param.setParams("sortStatus", pubSortInfo.getSortStatus());
		}
		if (Validator.isNotNull(pubSortInfo.getSortDisable())) {
			param.setParams("sortDisable", pubSortInfo.getSortDisable());
		}
		if (Validator.isNotNull(pubSortInfo.getReserved1())) {
			param.setParams("reserved1", pubSortInfo.getReserved1());
		}
		if (Validator.isNotNull(pubSortInfo.getReserved2())) {
			param.setParams("reserved2", pubSortInfo.getReserved2());
		}
		return param;
	}

	private CacheManager getCache() {
		return LoadCacheFactory.getInstance().getCacheManager("");
	}
}
